package com.cn.ant.modules.wechat.utils;


import com.cn.ant.common.utils.DateUtils;
import com.cn.ant.common.utils.Identities;
import com.cn.ant.common.utils.SpringContextHolder;
import com.cn.ant.modules.wechat.entity.WeiXinTikit;
import com.cn.ant.modules.wechat.entity.WeixinAccount;
import com.cn.ant.modules.wechat.service.WeiXinTikitService;
import com.cn.ant.modules.wechat.service.WeixinAccountServiceImpl;
import net.sf.json.JSONObject;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.ConnectException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 公众平台通用接口工具类
 *
 * @author liuyq
 * @date 2013-08-09
 */
public class WeixinUtil {
    // 获取access_token的接口地址（GET） 限200（次/天）
    public final static String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
    //获取tikit的接口地址（GET）
    public final  static  String access_tikit_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";
    // 菜单创建（POST） 限100（次/天）
    public static String menu_create_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
    //客服接口地址
    public static String send_message_url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=ACCESS_TOKEN";
    //
//    private static final ResourceBundle bundle  = ResourceBundle.getBundle("weixin");

    /**
     * 发起https请求并获取结果
     *
     * @param requestUrl    请求地址
     * @param requestMethod 请求方式（GET、POST）
     * @param outputStr     提交的数据
     * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
     */
    public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
        JSONObject jsonObject = null;
        StringBuffer buffer = new StringBuffer();
        try {
            // 创建SSLContext对象，并使用我们指定的信任管理器初始化
            TrustManager[] tm = {new MyX509TrustManager()};
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(requestUrl);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
            httpUrlConn.setSSLSocketFactory(ssf);

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            httpUrlConn.setRequestMethod(requestMethod);

            if ("GET".equalsIgnoreCase(requestMethod))
                httpUrlConn.connect();

            // 当有数据需要提交时
            if (null != outputStr) {
                OutputStream outputStream = httpUrlConn.getOutputStream();
                // 注意编码格式，防止中文乱码
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }

            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
            jsonObject = JSONObject.fromObject(buffer.toString());
            //jsonObject = JSONObject.fromObject(buffer.toString());
        } catch (ConnectException ce) {
            ce.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

    /**
     * 获取access_token
     *
     * @param appid     凭证
     * @param appsecret 密钥
     * @return
     */
    public static AccessToken getAccessToken(WeixinAccountServiceImpl accountService, String appid, String appsecret) {
        AccessTokenYw accessTocken = getRealAccessToken(accountService, appid);

        if (accessTocken != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date end = new Date();
            Date start = new Date(accessTocken.getAddTime().getTime());
            if (end.getTime() - accessTocken.getAddTime().getTime() > accessTocken.getExpires_in() * 1000) {
                AccessToken accessToken = null;
                String requestUrl = access_token_url.replace("APPID", appid).replace("APPSECRET", appsecret);
                JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
                // 如果请求成功
                if (null != jsonObject) {
                    try {
                        accessToken = new AccessToken();
                        accessToken.setToken(jsonObject.getString("access_token"));
                        accessToken.setExpiresIn(jsonObject.getInt("expires_in"));
                        //凭证过期更新凭证
                        AccessTokenYw atyw = new AccessTokenYw();
                        atyw.setId(accessTocken.getId());
                        atyw.setAppId(appid);
                        atyw.setExpires_in(jsonObject.getInt("expires_in"));
                        atyw.setAccess_token(jsonObject.getString("access_token"));
                        atyw.setAddTime(DateUtils.getCurrDate());
                        updateAccessToken(atyw, accountService);
                    } catch (Exception e) {
                        accessToken = null;
                        e.printStackTrace();
                        // 获取token失败
                        String wrongMessage = "获取token失败 errcode:{} errmsg:{}" + jsonObject.getInt("errcode") + jsonObject.getString("errmsg");
                        System.out.println(wrongMessage);
                    }
                }
                return accessToken;
            } else {
                AccessToken accessToken = new AccessToken();
                accessToken.setToken(accessTocken.getAccess_token());
                accessToken.setExpiresIn(accessTocken.getExpires_in());
                return accessToken;
            }
        } else {

            AccessToken accessToken = null;
            String requestUrl = access_token_url.replace("APPID", appid).replace("APPSECRET", appsecret);
            JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
            // 如果请求成功
            if (null != jsonObject) {
                try {
                    accessToken = new AccessToken();
                    accessToken.setToken(jsonObject.getString("access_token"));
                    accessToken.setExpiresIn(jsonObject.getInt("expires_in"));

                    AccessTokenYw atyw = new AccessTokenYw();
                    atyw.setId(Identities.generateUUID());
                    atyw.setAddTime(DateUtils.getCurrDate());
                    atyw.setExpires_in(jsonObject.getInt("expires_in"));
                    atyw.setAccess_token(jsonObject.getString("access_token"));
                    atyw.setAppId(appid);
                    saveAccessToken(atyw, accountService);

                } catch (Exception e) {
                    accessToken = null;
                    e.printStackTrace();
                    // 获取token失败
                    String wrongMessage = "获取token失败 errcode:{} errmsg:{}" + jsonObject.getString("errcode") + jsonObject.getString("errmsg");
                    System.out.println(wrongMessage);
                }
            }
            return accessToken;
        }
    }

    /**
     * 获取JSSDK的票根
     * @param tikitService
     * @param accessToken
     * @return
     */
    public static WeiXinTikit getWeixinTikit(WeiXinTikitService tikitService,String accessToken,String appId) {
        WeiXinTikit tikit = getRealTikit(tikitService, appId);
        if (tikit != null) {
            //更新tikit
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date end = new Date();
            Date start = new Date(tikit.getAddtime().getTime());
            if (end.getTime() - tikit.getAddtime().getTime() > tikit.getExpiresIn() * 1000) {
                String requestUrl = access_tikit_url.replace("ACCESS_TOKEN", accessToken);
                JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
                if (null != jsonObject) {
                    //请求成功
                    try {
                        tikit.setAddtime(DateUtils.getCurrDate());
                        tikit.setAppId(appId);
                        tikit.setTikit(jsonObject.getString("ticket"));
                        tikit.setExpiresIn(jsonObject.getInt("expires_in"));
                        tikitService.update(tikit);
                    } catch (Exception e) {
                        e.printStackTrace();
                        accessToken = null;
                        // 获取token失败
                        String wrongMessage = "获取tikit失败 errcode:{} errmsg:{}" + jsonObject.getInt("errcode") + jsonObject.getString("errmsg");
                        System.out.println(wrongMessage);
                    }

                }
            }
        } else {
            //查询tikit
            String requestUrl = access_tikit_url.replace("ACCESS_TOKEN", accessToken);
            JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
            if (null != jsonObject) {
                //请求成功
                try {
                    tikit = new WeiXinTikit();
                    tikit.setId(Identities.generateUUID());
                    tikit.setAppId(appId);
                    tikit.setAddtime(DateUtils.getCurrDate());
                    tikit.setTikit(jsonObject.getString("ticket"));
                    tikit.setExpiresIn(jsonObject.getInt("expires_in"));
                    tikitService.save(tikit);
                } catch (Exception e) {
                    e.printStackTrace();
                    accessToken = null;
                    // 获取token失败
                    String wrongMessage = "获取tikit失败 errcode:{} errmsg:{}" + jsonObject.getInt("errcode") + jsonObject.getString("errmsg");
                    System.out.println(wrongMessage);
                }
            }
        }
        return tikit;
    }


    /**
     * 从数据库中读取凭证
     *
     * @return
     */
    public static AccessTokenYw getRealAccessToken(WeixinAccountServiceImpl accountService, String appid) {
        AccessTokenYw accessTocken = accountService.getRealAccessToken(appid);
        return accessTocken;
    }

    public static WeiXinTikit getRealTikit(WeiXinTikitService tikitService, String appId) {
        List<WeiXinTikit> tikits = tikitService.queryForList(appId);
        if (tikits != null && tikits.size() > 0) {
            return tikits.get(0);
        } else {
            return null;
        }
    }

    /**
     * 保存凭证
     *
     * @return
     */
    public static void saveAccessToken(AccessTokenYw accessTocken, WeixinAccountServiceImpl accountService) {
        accountService.saveAccessToken(accessTocken);
    }

    /**
     * 更新凭证
     *
     * @return
     */
    public static void updateAccessToken(AccessTokenYw accessTocken, WeixinAccountServiceImpl accountService) {
        accessTocken.setAccess_token(accessTocken.getAccess_token());
        accessTocken.setExpires_in(accessTocken.getExpires_in());
        accessTocken.setAddTime(accessTocken.getAddTime());
        accountService.updateAccessToken(accessTocken);
    }


    /**
     * 编码
     *
     * @param bstr
     * @return String
     */
    public static String encode(byte[] bstr) {
        return new sun.misc.BASE64Encoder().encode(bstr);
    }

    /**
     * 解码
     *
     * @param str
     * @return string
     */
    public static byte[] decode(String str) {

        byte[] bt = null;
        try {
            sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
            bt = decoder.decodeBuffer(str);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bt;

    }

    /**
     * 获取登录用户微信账号信息
     * @return
     */
    public static final WeixinAccount getWeiXinAccount() {
        HttpSession session = SpringContextHolder.getSession();
        if(session.getAttribute(WeiXinConstants.WEIXIN_ACCOUNT)!=null){
            WeixinAccount WeixinAccountEntity = (WeixinAccount) session.getAttribute(WeiXinConstants.WEIXIN_ACCOUNT);
            return WeixinAccountEntity;
        }else{
            return null;
        }
    }

}